package com.skyworthclub.competition.config.db;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext.SerializationPair;

import java.time.Duration;

/** Redis 缓存配置类
 * @author li
 * @version 1.0
 * @since 18-11-25 下午12:21
 **/
@Configuration
public class RedisCacheConfig {
    @Bean
    public RedisCacheConfiguration configuration() {
        RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig();
        //设置统一的缓存有效时间为1小时,公共前缀
        configuration = configuration.entryTtl(Duration.ofHours(2)).prefixKeysWith("com.skyworthclub.competition:");
        // dev类加载器问题
        JdkSerializationRedisSerializer redisSerializer = new JdkSerializationRedisSerializer(getClass().getClassLoader());
        SerializationPair serializationPair = SerializationPair.fromSerializer(redisSerializer);

        return configuration.serializeValuesWith(serializationPair);
    }

    @Bean
    public RedisCacheManager redisCacheManager(RedisConnectionFactory connectionFactory) {
        RedisCacheWriter cacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory);
        return new RedisCacheManager(cacheWriter, configuration());
    }

}
